import { useOnGamePM } from '../helpers';
import type { TSvStatus } from '~comp/suspense';

export function useGameRecord(pmName: 'addMyLog' | 'addAllLog') {
  interface TLog {
    betAmount: string;
    profitAmount: string;
    rewardAmount: string;
    currency: string;
    multiplier: number;
    id: string;
    prizeStatus: number;
    time: number;
    user?: {
      level: number;
      uid: string;
      nickname: string;
      avatar: string;
    };
  }

  const MAX_LAN = 50;
  const pageSize = ref(10);
  const status = ref<TSvStatus>('pending');
  const list = ref<TLog[]>([]);
  const listSliced = computed(() => list.value.slice(0, pageSize.value));

  const add = (log: TLog) => {
    if (!log.time)
      return;

    const index = list.value.findIndex(item => item.id === log.id);

    if (index > -1) {
      // 如果日志已存在，则本次添加算作更新日志状态
      list.value[index] = log;
    }
    else {
      list.value = [log, ...list.value].sort((a, b) => b.time - a.time).slice(0, MAX_LAN);
    }

    status.value = 'success';
  };

  useOnGamePM(pmName, add);
  useOnGamePM('loaded', async () => {
    await sleep(1000);
    status.value = list.value.length ? 'success' : 'empty';
  });

  return reactive({ list: listSliced, pageSize, status, add });
}
